import { mapState, mapGetters, mapMutations } from 'vuex';
import axios from 'axios';
// import api from '../fetch/api'
import utils from './utils.js';

export default {
  mixins: [utils],
  data() {
    const today = [new Date(moment().format('YYYY-MM-DD 00:00:00')), new Date(moment().format('YYYY-MM-DD 23:59:59'))];
    const lastDay = [
      new Date(
        moment()
          .add(-1, 'days')
          .format('YYYY-MM-DD 00:00:00')
      ),
      new Date(
        moment()
          .add(-1, 'days')
          .format('YYYY-MM-DD 23:59:59')
      )
    ];
    const lastWeek = [
      new Date(
        moment()
          .add(-7, 'days')
          .format('YYYY-MM-DD 00:00:00')
      ),
      new Date(moment().format('YYYY-MM-DD 23:59:59'))
    ];
    const lastMonth = [
      new Date(
        moment()
          .add(-30, 'days')
          .format('YYYY-MM-DD 00:00:00')
      ),
      new Date(moment().format('YYYY-MM-DD 23:59:59'))
    ];
    const last3Month = [
      new Date(
        moment()
          .add(-90, 'days')
          .format('YYYY-MM-DD 00:00:00')
      ),
      new Date(moment().format('YYYY-MM-DD 23:59:59'))
    ];

    const afterDay = [
      new Date(moment().format('YYYY-MM-DD 00:00:00')),
      new Date(
        moment()
          .add(1, 'days')
          .format('YYYY-MM-DD 23:59:59')
      )
    ];
    const afterWeek = [
      new Date(moment().format('YYYY-MM-DD 00:00:00')),
      new Date(
        moment()
          .add(7, 'days')
          .format('YYYY-MM-DD 23:59:59')
      )
    ];
    const afterMonth = [
      new Date(moment().format('YYYY-MM-DD 00:00:00')),
      new Date(
        moment()
          .add(30, 'days')
          .format('YYYY-MM-DD 23:59:59')
      )
    ];
    const after3Month = [
      new Date(moment().format('YYYY-MM-DD 00:00:00')),
      new Date(
        moment()
          .add(30 * 3, 'days')
          .format('YYYY-MM-DD 23:59:59')
      )
    ];
    const afterYear = [
      new Date(moment().format('YYYY-MM-DD 00:00:00')),
      new Date(
        moment()
          .add(1, 'year').subtract(1, 'days').format('YYYY-MM-DD 23:59:59')
      )
    ];
    const after10Year = [
      new Date(moment().format('YYYY-MM-DD 00:00:00')),
      new Date(
        moment()
          .add(10, 'year').subtract(1, 'days').format('YYYY-MM-DD 23:59:59')
      )
    ];
    var self = this;
    return {
      // isDeactivated: false,
      treeSearchName: '',
      selectedNodeList: [],
      ztreeObj: null,
      item: this.dataObj,
      beforePickerOptions: {
        shortcuts: [
          {
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', today);
            }
          },
          {
            text: '昨天',
            onClick(picker) {
              picker.$emit('pick', lastDay);
            }
          },
          {
            text: '最近一周',
            onClick(picker) {
              picker.$emit('pick', lastWeek);
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              picker.$emit('pick', lastMonth);
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              picker.$emit('pick', last3Month);
            }
          }
        ]
      },
      afterPickerOptions: {
        shortcuts: [
          {
            text: '后一天',
            onClick(picker) {
              picker.$emit('pick', afterDay);
            }
          },
          {
            text: '后一周',
            onClick(picker) {
              picker.$emit('pick', afterWeek);
            }
          },
          {
            text: '后一个月',
            onClick(picker) {
              picker.$emit('pick', afterMonth);
            }
          },
          {
            text: '后三个月',
            onClick(picker) {
              picker.$emit('pick', after3Month);
            }
          },
          {
            text: '后一年',
            onClick(picker) {
              picker.$emit('pick', afterYear);
            }
          },
          {
            text: '后十年',
            onClick(picker) {
              picker.$emit('pick', after10Year);
            }
          }
        ],
        //定义minDate_参数才会生效，设置最少的可选日期
        disabledDate: function(dayArr_) {
          var result = false;
          if (self.minDate_) {
            if (self.minDate_.getTime() <= dayArr_.getTime()) {
              result = false;
            } else {
              result = true;
            }
          } else {
            result = false;
          }
          return result;
        }
      }
    };
  },
  computed: {
    ...mapGetters({
      perms: Object.freeze('getPerms'),
      isDialog: 'getIsDialog'
    }),
    ...mapState(['carrierId'])
  },
  methods: {
    ...mapMutations({
      loadingToggle: 'LOADING_TOGGLE',
      dialogToggle: 'DIALOG_TOGGLE',
      setDialog: 'SET_DIALOG'
    }),
    search_ztree(zTreeId) {
      this.ztreeObj = $.fn.zTree.getZTreeObj(zTreeId);
      if (this.treeSearchName) {
        this.searchNodes();
      }
    },
    searchNodes() {
      let _this = this;
      let treeObj = this.ztreeObj;
      let Val = this.treeSearchName;
      this.updateNodes(false);
      if (Val) {
        let txt = this.splitWord(Val);
        this.selectedNodeList = treeObj.getNodesByParamFuzzy('name', txt);
        this.updateNodes(true);
        if (this.selectedNodeList.length == 0) {
          this.showToast('没有搜索到相匹配的数据！', 2, 1000, function() {
            _this.treeSearchName = '';
          });
        } else {
          _this.showToast('搜索成功', 1);
        }
      }
    },
    updateNodes(highlight) {
      let zTree = this.ztreeObj,
        nodeList = this.selectedNodeList;
      for (var i = 0, l = nodeList.length; i < l; i++) {
        if (highlight && nodeList[i].getParentNode()) {
          zTree.expandNode(nodeList[i].getParentNode(), true, false, true);
        }
        nodeList[i].highlight = highlight;
        zTree.updateNode(nodeList[i]);
      }
    },
    splitWord(str) {
      if (str.indexOf('(') != -1) {
        var strs = str.split('(', 2);
        return strs[0];
      } else {
        return str;
      }
    },
    //處理ajax请求返回的数据
    getData(response) {
      let promise = new Promise(function(resolve, reject) {
        let res = response.data;
        let success = res.success;
        let data = res.data;
        if (success) {
          if (data) {
            resolve(data);
          } else {
            resolve(success);
          }
        } else {
          reject(res);
        }
      });
      return promise;
    },
    toExport(url, params) {
      axios
        .get(url, {
          params: params,
          timeout: 50000
        })
        .then(
          response => {
            // console.log('ExportResult', response)
            let data = response.data.data;
            if (data && data.indexOf('http') == 0) {
              window.location.href = data;
            } else {
              this.$store.dispatch('toastToggle', {
                info: response.data.message,
                isToasting: true,
                time: 2000,
                icon: 1
              });
              window.location.href = encodeURI('../mgr/common/download.do?fileName=' + data);
            }
          },
          err => {
            this.$store.dispatch('toastToggle', {
              info: response.data.message,
              isToasting: true,
              time: 2000,
              icon: 2
            });
          }
        )
        .catch(error => {
          // console.log("Export-Error")
        });
    },
    toExportAsync(url, params) {
      axios
        .get(url, {
          params: params,
          timeout: 50000
        })
        .then(
          response => {
            let data = response.data.data;
            if (data && data.indexOf('http') == 0) {
              window.location.href = data;
            } else {
              if (response.data.status == 1) {
                this.$store.dispatch('toastToggle', {
                  info: '操作成功，请打开右上角下载中心界面进行下载',
                  isToasting: true,
                  time: 5000,
                  icon: 1
                });
              }
            }
          },
          err => {
            this.$store.dispatch('toastToggle', {
              info: response.data.message,
              isToasting: true,
              time: 2000,
              icon: 2
            });
          }
        )
        .catch(error => {
          
        });
    },
    formatDate(needTime) {
      //needTime是整数，否则要parseInt转换
      var time = new Date(needTime);
      var y = time.getFullYear();
      var m = time.getMonth() + 1;
      var d = time.getDate();
      var h = time.getHours();
      var mm = time.getMinutes();
      var s = time.getSeconds();
      return (
        y + '-' + this.add0(m) + '-' + this.add0(d) + ' ' + this.add0(h) + ':' + this.add0(mm) + ':' + this.add0(s)
      );
    }
  }
};
